import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Arrays;

public class ValArff {
	static int mode;
	static String PATH_WEKA;

	static String PATH_LABEL = "../LABELS.txt";
	static byte[] label;
	static int ROWS;

	static String PATH_INPUT = "../val";
	static byte[][] input;
	static File[] listOfFiles;
	static int COLS;

	public static void main(String[] args) throws Exception {
		if (args.length > 0) {
			mode = Integer.valueOf(args[0]);
		} else {
			mode = 0;
		}
		PATH_WEKA = "../val" + mode + ".arff";

		readLabel_ROWS();
		readInputs_COLS();

		echo();

		writeArff();

		ROWS = 90000;
		PATH_WEKA = PATH_WEKA.replace("arff", "small.arff");
		writeArff();
	}

	private static void readLabel_ROWS() throws Exception {
		File file = new File(PATH_LABEL);
		FileInputStream fis = new FileInputStream(file);
		ROWS = (int) file.length();
		label = new byte[ROWS];

		fis.read(label);
	}

	private static void readInputs_COLS() throws Exception {
		File folder = new File(PATH_INPUT);
		listOfFiles = folder.listFiles();
		Arrays.sort(listOfFiles);
		COLS = listOfFiles.length;
		input = new byte[COLS][ROWS];

		for (int c = 0; c < COLS; c++) {
			if (listOfFiles[c].isFile()) {
				FileInputStream fis = new FileInputStream(listOfFiles[c]);
				fis.read(input[c]);
			}
		}
	}

	private static void echo() {
		System.out.printf("  %6s ", "a:");
		for (int c = 0; c < COLS; c++) {
			String fileName = listOfFiles[c].getName();
			String attName = fileName.substring(0, 5);
			System.out.printf("%6s", attName);
		}
		System.out.println(" label");

		for (int r = 0; r < 30; r++) {
			System.out.printf("%5d  : ", r);

			for (int c = 0; c < COLS; c++) {
				System.out.printf("% 6d", input[c][r]);
			}
			System.out.printf(" %6s \n", (label[r] + 5) / 10 * 10);
		}
		System.out.println("mode: " + mode);
	}

	private static void writeArff() throws Exception {
		FileWriter fw = new FileWriter(PATH_WEKA);
		BufferedWriter bw = new BufferedWriter(fw);

		bw.write("@relation r\n");
		for (int c = 0; c < COLS; c++) {
			String fileName = listOfFiles[c].getName();
			String attName = fileName.substring(0, 5);
			bw.write("@attribute " + attName + " numeric\n");
		}

		if (mode < 2) {
			bw.write("@attribute label numeric\n");
		} else {
			bw.write("@attribute label "
					+ "{0,10,20,30,40,50,60,70,80,90,100}\n");
		}
		bw.write("@data\n");

		for (int r = 0; r < ROWS; r++) {
			for (int c = 0; c < COLS; c++) {
				bw.write(input[c][r] + ",");
			}
			if (mode < 1) {
				bw.write(label[r] + "\n");
			} else {
				bw.write(((label[r] + 5) / 10 * 10) + "\n");
			}
		}
		bw.close();
	}
}
